<template>
  <div class="manage">
    <el-dialog :title="operateType === 'add' ? '新增角色' : '更新角色'" :visible.sync="isShow">
      <template>
        <el-form :inline="false" :model="operateForm" :rules="operateRules" ref="operateForm" label-width="100px">
          <el-form-item key="roleCode" label="角色编码" prop="roleCode">
            <el-input v-model="operateForm.roleCode" placeholder="请输入角色编码"></el-input>
          </el-form-item>

          <el-form-item key="roleName" label="角色名称" prop="roleName">
            <el-input v-model="operateForm.roleName" placeholder="请输入角色名称"></el-input>
          </el-form-item>

          <el-form-item key="selectedData" label="权限" prop="selectedData">
            <tree-select :height="400"
                         :width="400"
                         size="small"
                         :data="treeData"
                         :defaultProps="defaultProps"
                         :nodeKey="nodeKey"
                         :checkedKeys="defaultCheckedKeys"
                         multiple
                         clearable
                         collapseTags
                         checkStrictly ref="tree">
            </tree-select>
          </el-form-item>

          <el-form-item>
            <slot></slot>
          </el-form-item>
        </el-form>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShow = false">取 消</el-button>
        <el-button type="primary" @click="confirm('operateForm')">确 定</el-button>
      </div>
    </el-dialog>
    <div class="manage-header">
      <el-button type="primary" v-per="'save'" @click="addRole()">+ 新增</el-button>
      <template>
        <el-form :inline="true" :model="searchFrom" ref="searchFrom" label-width="100px" >
          <el-form-item key="keyword" label="角色名称/编码" >
            <el-input v-model="searchFrom.keyword" placeholder="请输入角色名称/编码"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getList(searchFrom.keyword)">搜索</el-button>
          </el-form-item>
        </el-form>
      </template>

    </div>
    <common-table :tableData="tableData" :tableLabel="tableLabel" :config="config" @changePage="getList()"
                  @edit="editRole" @del="delRole"></common-table>
  </div>
</template>

<script>
import CommonTable from '../../components/CommonTable'
import TreeSelect from '../../components/TreeSelect'
import store from "@/store";

export default {
  components: {
    CommonTable,
    TreeSelect
  },
  data() {
    return {
      nodeKey: 'id',
      defaultCheckedKeys: [],
      defaultProps: {
        parent: 'parentId',   // 父级唯一标识
        value: 'id',          // 唯一标识
        label: 'label',       // 标签显示
        children: 'children', // 子级
      },
      operateType: 'add',
      isShow: false,
      treeData: [],
      tableData: [],
      tableLabel: [
        {
          prop: 'roleCode',
          label: '角色编码'
        },
        {
          prop: 'roleName',
          label: '角色名称'
        },
        {
          prop: 'updateTime',
          label: '更新时间',
          width: 320
        }
      ],
      config: {
        page: 1,
        total: 30,
        pageSize:10,
        loading: false
      },
      operateForm: {
        roleCode: '',
        roleName: '',
        permissions:[]
      },
      operateRules: {
        roleCode: [
          {required: true, message: '请输入角色名称', trigger: 'blur'},
          {max: 32, message: '角色编码不超过32个字符', trigger: 'blur'}
        ],
        roleName: [
          {required: true, message: '请输入角色名称', trigger: 'blur'},
          {max: 32, message: '用户名长度不大于 32 个字符', trigger: 'blur'}
        ]
      },
      searchFrom: {
        keyword: ''
      }
    }
  },
  methods: {
    getTreeData() {
      this.config.loading = true
      store.commit('getToken')
      let token = store.state.user.token
      this.$http
          .get('http://localhost:8001/api/manager/permission/listPermissionTreeWithBtn', {
            params: {
              keyword: ''
            },
            headers: {
              "token": token
            }
          })
          .then(res => {
            this.treeData = res.data
          })
    },
    getList(keyword = '') {
      console.log('列表搜索' + keyword)
      this.config.loading = true
      // 搜索时，页码需要设置为1，才能正确返回数据，因为数据是从第一页开始返回的
      keyword ? (this.config.page = 1) : ''
      store.commit('getToken')
      let token = store.state.user.token

      this.$http
          .get('http://localhost:8001/api/manager/role/list', {
            params: {
              page: this.config.page,
              pageSize: this.config.pageSize,
              keyword
            },
            headers: {
              "token": token
            }
          })
          .then(res => {
            this.tableData = res.data.records
            this.config.total = res.data.total
            this.config.loading = false
          })
    },
    addRole() {
      this.operateForm = {}
      this.operateType = 'add'
      this.isShow = true
    },
    editRole(row) {
      this.operateType = 'edit'
      this.isShow = true
      this.operateForm = row
      this.defaultCheckedKeys = row.permissions
      if (this.$refs.tree) {
        this.$refs.tree.initCheckedData();
      }
    },
    confirm(form) {
      console.log(this.$refs['tree'].selectedData)
      this.$refs[form].validate((valid) => {
        if (valid) {
          this.operateForm.permissions = this.$refs['tree'].selectedData

          store.commit('getToken')
          let token = store.state.user.token
          if (this.operateType === 'edit') {
            console.log(this.operateForm)
            this.$http.post('http://localhost:8001/api/manager/role/update', this.operateForm, {
              headers: {
                "token": token
              }
            }).then(res => {
              console.log(res.data)
              this.isShow = false
              this.getList()
            })
          } else {
            this.$http.post('http://localhost:8001/api/manager/role/save', this.operateForm, {
              headers: {
                "token": token
              }
            }).then(res => {
              console.log(res.data)
              this.isShow = false
              this.getList()
            })
          }
        }
      });

    },
    delRole(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
          .then(() => {
            let id = row.id
            store.commit('getToken')
            let token = store.state.user.token
            this.$http
                .delete('http://localhost:8001/api/manager/role/delete/' + id, {
                  headers: {
                    token: token
                  }
                })
                .then(res => {
                  console.log(res.data)
                  this.$message({
                    type: 'success',
                    message: res.data.message
                  })
                  this.getList()
                })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
    }
  },
  created() {
    this.getList()
    this.getTreeData()
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/scss/common';
</style>
